﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace ERefCommon
{
    /// <summary>
    /// 时间json序列化转换器
    /// </summary>
    internal class JsonDateTimeConverter : JsonConverter<DateTime>
    {
        /// <summary>
        /// 默认格式化字符串
        /// </summary>
        private string _fmtStr = "yyyy-MM-dd HH:mm:ss";
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="fmtStr">格式化字符串</param>
        public JsonDateTimeConverter(string fmtStr= "yyyy-MM-dd HH:mm:ss") 
        {
            if (!string.IsNullOrWhiteSpace(fmtStr)) 
            {
                _fmtStr = fmtStr;
            }            
        }
        /// <summary>
        /// 读取行为
        /// </summary>
        /// <param name="reader">读取器</param>
        /// <param name="typeToConvert">类型转换</param>
        /// <param name="options">选项</param>
        /// <returns>读取后的值</returns>
        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.String)
            {
                if (DateTime.TryParse(reader.GetString(), out DateTime date)) 
                {
                    return date;
                }
            }
            return reader.GetDateTime();
        }
        /// <summary>
        /// 写入行为
        /// </summary>
        /// <param name="writer">写入器</param>
        /// <param name="value">值</param>
        /// <param name="options">选项</param>
        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString(_fmtStr));
        }
    }
}
